local newt = reload("newt")
local cowork = reload("thread.work")
local delay = reload("timer.delayms")
---挂起
local function await(carg, ...)
    return coroutine.yield(...)
end

---恢复
local function coback(carg, ...)
    carg.co(...)
end

---数据
local function codata(carg, data, key, ret)
    data[key] = ret
end

---延迟
local function codelay(carg, ms)
    delay(carg, carg, ms)
    carg:await()
end

---异步标记
---@param no boolean @不自动生成标记
local function comark(carg, no)
    local counter = carg.counter or 0
    carg.counter = counter + 1
    if not no then
        return carg:codefer()
    end
end

---异步确认
local function confirm(carg)
    local counter = carg.counter or 0
    carg.counter = counter - 1
    if 1 == counter then
        carg:coback()
    end
end

---延后确认(标记确认)
local function codefer(carg)
    if not carg.clofirm then
        function carg.clofirm()
            carg:confirm()
        end
    end
    return carg.clofirm
end

---提前结束线程(需要代码支持)
local function coexit(carg)
    carg.exit = true
    carg.co()
end

return function (func, ...)
    local co = cowork()
    local carg = newt()
    carg.co = co
    carg.await = await
    carg.coback = coback
    carg.codata = codata
    carg.codelay = codelay
    carg.comark = comark
    carg.confirm = confirm
    carg.codefer = codefer
    carg.coexit = coexit
    local ls = { carg, ... }
    ls.carg = carg
    co(func, ls)
end
